//
//  LSYWebView.m
//  TTClub
//
//  Created by RoyLei on 15/10/21.
//  Copyright © 2015年 TTClub. All rights reserved.
//

#import "LSYWebView.h"
#import "LKJsonRequestManager.h"
#import <GKPhotoBrowser/GKPhotoBrowser.h>
#import "BNDConstance.h"


NSString *LSYWebViewCompleteRPCURLPath = @"/webviewCtrlprogressproxy/complete";

const float LSYWebViewCtrlInitialProgressValue           = 0.1f;
const float LSYWebViewCtrlInteractiveProgressValue       = 0.5f;
const float LSYWebViewCtrlFinalProgressValue             = 0.9f;

const NSUInteger TTNSURLRequestTimeOut = 10;
NSString * const LSYCachingURLMarkHeader = @"LSYCachingURLMarkHeader";


@interface LSYWebView()<WKNavigationDelegate,WKUIDelegate>

@property (copy, nonatomic,   readwrite) NSString *urlString;
@property (strong, nonatomic, readwrite) NSURL  *currentURL;
@property (strong, nonatomic, readwrite) NSMutableURLRequest *currentRequest;
@property (strong, nonatomic, readwrite) NSMutableArray *imageArray;

@end

@implementation LSYWebView

- (instancetype)initWithFrame:(CGRect)frame configuration:(nonnull WKWebViewConfiguration *)configuration
{
    
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
   
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;

    self = [super initWithFrame:frame configuration:wkWebConfig];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)dealloc
{
    [self webViewloadingStatus:NO];
    [self.scrollView removeObserver:self forKeyPath:@"contentSize"];
}

- (void)commonInit
{

    [self setOpaque:NO];
    self.allowsBackForwardNavigationGestures = YES;
    self.UIDelegate = self;
    self.navigationDelegate = self;
    [self setBackgroundColor:UIColorWithHex(0xffffff)];
  
    [self.scrollView setMinimumZoomScale:1.0f];
    [self.scrollView setMaximumZoomScale:1.0f];
    
    [self.scrollView addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:nil];
    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    BND_BLOCK_EXEC(self.hightBlock,self.scrollView.contentSize.height);
}

- (void)webViewloadingStatus:(BOOL)loading {
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:loading];
}


#pragma mark - Start load web page

- (void)loadWebPage:(NSString *)htmlText
{
    if(htmlText.length ==0) {
        htmlText = @"";
    }
    
        NSString *htmlString = [NSString stringWithFormat:@"<html> \n"
                                "<head> \n"
                                "<style type=\"text/css\"> \n"
                                "body {font-size:14px;}\n"
                                "</style> \n"
                                "</head> \n"
                                "<body>"
                                "<script type='text/javascript'>"
                                "window.onload = function(){\n"
                                "var $img = document.getElementsByTagName('img');\n"
                                "for(var p in  $img){\n"
                                " $img[p].style.width = '100%%';\n"
                                "$img[p].style.height ='auto'\n"
                                "}\n"
                                "}"
                                "</script>%@"
                                "</body>"
                                "</html>",htmlText];
    
    
    
    [self loadHTMLString:htmlString baseURL:nil];
    
}

- (NSMutableURLRequest *)setupUrlRequestWithUrl:(NSString *)urlString
{
    self.urlString = urlString;
    
    NSURL *url = [NSURL URLWithString:self.urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:TTNSURLRequestTimeOut];
    
    [request setAllHTTPHeaderFields:[LKJsonRequestManager commonHTTPHeaderField]];
    [request addValue:LSYCachingURLMarkHeader forHTTPHeaderField:LSYCachingURLMarkHeader];
    [request setHTTPMethod:@"POST"];
    self.currentRequest = request;
    
    return request;
}

- (NSString *)noScaleJSString
{
    return @"function setScale(){\
    var all_metas=document.getElementsByTagName('meta');\
    if (all_metas){\
    var k;\
    for (k=0; k<all_metas.length;k++){\
    var meta_tag=all_metas[k];\
    var viewport= meta_tag.getAttribute('name');\
    if (viewport&& viewport=='viewport'){\
    meta_tag.setAttribute('content',\"width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\");\
    }\
    }\
    }\
    }";
}

#pragma mark - WKWebView

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
{
    //    if ([_webViewProxyDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
    //        [_webViewProxyDelegate webViewDidStartLoad:webView];
    //    }
    [self webViewloadingStatus:YES];
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self webViewloadingStatus:NO];
    [self addImgClickJS];
    
    if ([_webViewProxyDelegate respondsToSelector:@selector(wk_didFinishNavigation)]) {
        [_webViewProxyDelegate wk_didFinishNavigation];
    }
    
    
    NSString *injectionJSString = @"var script = document.createElement('meta');"
    "script.name = 'viewport';""script.content=\"width=device-width, user-scalable=no\";""document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#80858C'"completionHandler:nil];
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];

    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [self webViewloadingStatus:NO];
    
    if ([_webViewProxyDelegate respondsToSelector:@selector(wk_didFailProvisionalNavigation)]) {
        [_webViewProxyDelegate wk_didFailProvisionalNavigation];
    }
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    //预览图片

    if ([_webViewProxyDelegate respondsToSelector:@selector(wk_decidePolicyForNavigationAction)]) {
        [_webViewProxyDelegate wk_decidePolicyForNavigationAction];
    }
    
    
    NSURL * url = navigationAction.request.URL;
    if ([url.scheme isEqualToString:@"image-preview-index"]) {
        //图片点击回调
        NSInteger index = [[url.absoluteString substringFromIndex:[@"image-preview-index:" length]] integerValue];
        NSString * imgPath = self.imageArray.count > index?self.imageArray[index]:nil;
        
        
        NSMutableArray *photos = [NSMutableArray new];
        GKPhoto *photo = [GKPhoto new];
        photo.url = [NSURL URLWithString:imgPath];
        [photos addObject:photo];
        GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photos currentIndex:0];
        browser.showStyle = GKPhotoBrowserShowStyleNone;
        [browser showFromVC:[BNDPushVCHandler currentSelectedNavController]];
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

- (void)addImgClickJS
{
    
    //获取所以的图片标签
    [self evaluateJavaScript:@"function getImages(){\
     var imgs = document.getElementsByTagName('img');\
     var imgScr = '';\
     for(var i=0;i<imgs.length;i++){\
     if (i == 0){ \
     imgScr = imgs[i].src; \
     } else {\
     imgScr = imgScr +'***'+ imgs[i].src;\
     } \
     };\
     return imgScr;\
     };" completionHandler:nil];//注入js方法
    
    __weak typeof(self)weakSelf = self;
    [self evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        if (!error) {
            
            NSMutableArray * urlArray = result?[NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"***"]]:nil;
            weakSelf.imageArray = urlArray;
        } else {
            weakSelf.imageArray = nil;
        }
    }];
    
    
    //添加图片点击的回调
    [self evaluateJavaScript:@"function registerImageClickAction(){\
     var imgs = document.getElementsByTagName('img');\
     for(var i=0;i<imgs.length;i++){\
     imgs[i].customIndex = i;\
     imgs[i].onclick=function(){\
     window.location.href='image-preview-index:'+this.customIndex;\
     }\
     }\
     }" completionHandler:nil];
    [self evaluateJavaScript:@"registerImageClickAction();" completionHandler:nil];
}





@end
